package com.rede.didiok.community.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.RedisConf;
import com.rede.didiok.common.constant.conf.SQLConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.conf.base.BaseSQLConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.domainEvent.EventAction;
import com.rede.didiok.common.dto.community.MomentCommentDto;
import com.rede.didiok.common.dto.user.UserDto;
import com.rede.didiok.common.enums.*;
import com.rede.didiok.common.exception.exceptionType.FeignException;
import com.rede.didiok.common.feign.AdminFeignClient;
import com.rede.didiok.common.feign.UserFeignClient;
import com.rede.didiok.common.holder.RequestHolder;
import com.rede.didiok.common.utils.*;
import com.rede.didiok.common.utils.business.DomainEventUtil;
import com.rede.didiok.common.utils.business.FileFeignUtil;
import com.rede.didiok.common.utils.business.UserUtil;
import com.rede.didiok.community.dao.MomentCommentDao;
import com.rede.didiok.community.entity.MomentCommentEntity;
import com.rede.didiok.community.entity.UserMomentEntity;
import com.rede.didiok.community.service.MomentCommentService;
import com.rede.didiok.community.service.UserMomentService;


@Service("momentCommentService")
public class MomentCommentServiceImpl extends ServiceImpl<MomentCommentDao, MomentCommentEntity> implements MomentCommentService {


    @Resource
    private MomentCommentDao momentCommentDao;
    @Resource
    private UserMomentService userMomentService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private AdminFeignClient adminFeignClient;
    @Resource
    private FileFeignUtil fileFeignUtil;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserUtil userUtil;
    @Autowired
    private AdminFeignClient adminService;
    /**
     * 领域事件工具类
     */
    @Resource
    private DomainEventUtil domainEventUtil;


    /***************************** admin:start **************************/
    // region  didiok-admin

    @Override
    public IPage<MomentCommentEntity> getPageList(MomentCommentDto commentDto) {
        QueryWrapper<MomentCommentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(commentDto.getKeyword()) && !StringUtils.isEmpty(commentDto.getKeyword().trim())) {
            queryWrapper.like(SQLConf.CONTENT, commentDto.getKeyword().trim());
        }

        if (commentDto.getType() != null) {
            queryWrapper.eq(SQLConf.TYPE, commentDto.getType());
        }

        if (StringUtils.isNotEmpty(commentDto.getSource()) && !SysConf.ALL.equals(commentDto.getSource())) {
            queryWrapper.eq(SQLConf.SOURCE, commentDto.getSource());
        }
        if (null != commentDto.getAuditStatus()) {
            queryWrapper.eq(SQLConf.AUDIT_STATUS, commentDto.getAuditStatus());
        }

        if (StringUtils.isNotEmpty(commentDto.getCreateUserName())) {

            String userName = commentDto.getCreateUserName();

            // 从 redis中获取用户信息
            String userJson = redisUtil.get(RedisConf.USER_INFO_BY_NICKNAME + Constants.SYMBOL_COLON + userName);
            List<UserDto> list;
            if (StringUtils.isNotEmpty(userJson)) {
                list = (List<UserDto>)JsonUtils.jsonArrayToArrayList(userJson);
            }else {
                // 根据用户名获取用户信息
                R result = userFeignClient.getByNickname(userName);
                if(result.getCode()==0){
                    list = result.getData(new TypeReference<List<UserDto>>(){});
                    // TODO 这里只有存储，但是没有写删除
                    redisUtil.setEx(RedisConf.USER_INFO_BY_NICKNAME + Constants.SYMBOL_COLON + userName, JsonUtils.objectToJson(list), 2, TimeUnit.HOURS);
                }else {
                    // 获取异常信息
                    String msg = result.getData("msg",new TypeReference<String>(){});
                    throw new FeignException("feign调用异常（根据用户名获取用户信息）："+msg);
                }
            }

            if (list.size() > 0) {
                List<String> userUid = new ArrayList<>();
                list.forEach(item -> {
                    userUid.add(item.getUid());
                });
                queryWrapper.in(SQLConf.CREATE_USER_UID, userUid);
            } else {
                // 当没有查询到用户时，默认UID
                queryWrapper.in(SQLConf.CREATE_USER_UID, SysConf.DEFAULT_UID);
            }
        }

        Page<MomentCommentEntity> page = new Page<>();
        page.setCurrent(commentDto.getCurrentPage());
        page.setSize(commentDto.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        IPage<MomentCommentEntity> pageList = this.page(page, queryWrapper);
        List<MomentCommentEntity> commentList = pageList.getRecords();
        pageList.setRecords(this.convertCommentList(commentList));
        return pageList;
    }

    @Override
    public List<MomentCommentEntity> convertCommentList(Collection<MomentCommentEntity> commentList) {
        List<MomentCommentEntity> resultList = new ArrayList<>();
        if (commentList.size() == 0) {
            return resultList;
        }
        Set<String> userUidSet = new HashSet<>();
        Set<String> blogUidSet = new HashSet<>();
        Set<String> questionUidSet = new HashSet<>();
        Set<String> problemUidSet = new HashSet<>();
        commentList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getCreateUserUid())) {
                userUidSet.add(item.getCreateUserUid());
            }
            if (StringUtils.isNotEmpty(item.getToUserUid())) {
                userUidSet.add(item.getToUserUid());
            }

            if (StringUtils.isNotEmpty(item.getMomentUid())) {
                if (CommentSourceEnum.USER_MOMENT.getCode().equals(item.getSource())) {
                    blogUidSet.add(item.getMomentUid());
                }
            }
        });

        // 获取博客
        Collection<UserMomentEntity> rankMemberList = new ArrayList<>();
        if (blogUidSet.size() > 0) {
            rankMemberList = userMomentService.listByIds(blogUidSet);
        }
        Map<String, UserMomentEntity> userMomentMap = new HashMap<>();

        rankMemberList.forEach(item -> {
            // 评论管理并不需要查看博客内容，因此将其排除
            item.setContent("");
            userMomentMap.put(item.getUid(), item);
        });

        // 根据用户uid列表查询用户
        List<String> userUidList = userUidSet.stream().collect(Collectors.toList());
        R result = userFeignClient.listUserByUids(userUidList);
        List<UserDto> userDtoList;
        if(result.getCode()==0){
            userDtoList = result.getData(new TypeReference<List<UserDto>>(){});
        }else {
            throw new FeignException("feign调用异常（根据用户uid列表查询用户）：失败");
        }
        // 获取头像
        List<String> fileUidList = new ArrayList<>();
        userDtoList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar())) {
                fileUidList.add(item.getAvatar());
            }
        });

        Map<String, String> pictureMap = fileFeignUtil.fileUidToFileUrlMap(fileUidList);

        // 用户信息脱敏
        userDtoList = userUtil.convertUserList(userDtoList);

        Map<String, UserDto> userMap = new HashMap<>();
        userDtoList.forEach(item -> {
            // 判断头像是否为空
            if (pictureMap.get(item.getAvatar()) != null) {
                item.setPhotoUrl(pictureMap.get(item.getAvatar()));
            }
            userMap.put(item.getUid(), item);
        });

        for (MomentCommentEntity item : commentList) {
            try {
                CommentSourceEnum commentSource = CommentSourceEnum.valueOf(item.getSource());
                item.setSourceName(commentSource.getName());
            } catch (Exception e) {
                log.error("CommentSourceEnum 转换异常");
            }

            if (StringUtils.isNotEmpty(item.getCreateUserUid())) {
                item.setUser(userMap.get(item.getCreateUserUid()));
            }
            if (StringUtils.isNotEmpty(item.getToUserUid())) {
                item.setToUser(userMap.get(item.getToUserUid()));
            }

            if (StringUtils.isNotEmpty(item.getMomentUid())) {
                if (CommentSourceEnum.USER_MOMENT.getCode().equals(item.getSource())) {
                    item.setUserMoment(userMomentMap.get(item.getMomentUid()));
                }
            }
            resultList.add(item);
        }
        return resultList;
    }


    @Override
    public String addComment(MomentCommentDto momentCommentDto) {
        MomentCommentEntity comment = new MomentCommentEntity();
        comment.setSource(momentCommentDto.getSource());
        comment.setMomentUid(momentCommentDto.getMomentUid());
        comment.setContent(momentCommentDto.getContent());
        comment.setCreateUserUid(momentCommentDto.getCreateUserUid());
        comment.setToUid(momentCommentDto.getToUid());
        comment.setToUserUid(momentCommentDto.getToUserUid());
        comment.setStatus(StatusEnum.ENABLE);
        boolean isSave = comment.insert();
        if (isSave) {
            MomentCommentDto dto = new MomentCommentDto();
            BeanUtils.copyProperties(comment, dto);
            domainEventUtil.publishEvent(EventAction.MOMENT_COMMENT_ADD, dto);
        }
        return MessageConf.INSERT_SUCCESS;
    }

    @Override
    public String editComment(MomentCommentDto momentCommentDto) {
        MomentCommentEntity comment = this.getById(momentCommentDto.getUid());
        comment.setSource(momentCommentDto.getSource());
        comment.setMomentUid(momentCommentDto.getMomentUid());
        comment.setContent(momentCommentDto.getContent());
        comment.setCreateUserUid(momentCommentDto.getCreateUserUid());
        comment.setToUid(momentCommentDto.getToUid());
        comment.setToUserUid(momentCommentDto.getToUserUid());
        comment.setStatus(StatusEnum.ENABLE);
        boolean isSave = comment.updateById();
        if (isSave) {
            MomentCommentDto dto = new MomentCommentDto();
            BeanUtils.copyProperties(comment, dto);
            domainEventUtil.publishEvent(EventAction.MOMENT_COMMENT_EDIT, dto);
        }
        return MessageConf.UPDATE_SUCCESS;
    }

    @Override
    public String deleteComment(MomentCommentDto momentCommentDto) {
        MomentCommentEntity comment = this.getById(momentCommentDto.getUid());
        comment.setStatus(StatusEnum.DISABLED);
        boolean isSave = comment.updateById();
        if (isSave) {
            MomentCommentDto dto = new MomentCommentDto();
            BeanUtils.copyProperties(comment, dto);
            domainEventUtil.publishEvent(EventAction.MOMENT_COMMENT_DELETE, dto);
        }
        return MessageConf.DELETE_SUCCESS;
    }

    @Override
    public String deleteBatchComment(List<MomentCommentDto> momentCommentDtoList) {
        if (momentCommentDtoList.size() == 0) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();
        momentCommentDtoList.forEach(item -> {
            uids.add(item.getUid());
        });
        Collection<MomentCommentEntity> commentList = this.listByIds(uids);

        commentList.forEach(item -> {
            item.setStatus(StatusEnum.DISABLED);
            MomentCommentDto dto = new MomentCommentDto();
            BeanUtils.copyProperties(item, dto);
            domainEventUtil.publishEvent(EventAction.MOMENT_COMMENT_DELETE, dto);
        });
        this.updateBatchById(commentList);
        return MessageConf.DELETE_SUCCESS;
    }

    // endregion
    /***************************** admin:end **************************/



    /***************************** web:start **************************/
    // region didiok-web

    /**
     * 获取用户评论列表
     *
     * @param commentDto@return
     */
    @Override
    public IPage<MomentCommentEntity> getUserCommentList(MomentCommentDto commentDto) {
        QueryWrapper<MomentCommentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(commentDto.getMomentUid())) {
            queryWrapper.like(SQLConf.MOMENT_UID, commentDto.getMomentUid());
        }
        queryWrapper.eq(SQLConf.SOURCE, commentDto.getSource());
        //分页
        Page<MomentCommentEntity> page = new Page<>();
        page.setCurrent(commentDto.getCurrentPage());
        page.setSize(commentDto.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.eq(SQLConf.AUDIT_STATUS, AuditStatusEnum.AGREE);
        queryWrapper.isNull(SQLConf.TO_UID);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        queryWrapper.eq(SQLConf.TYPE, CommentTypeEnum.COMMENT);
        // 查询出所有的一级评论，进行分页显示
        IPage<MomentCommentEntity> pageList = this.page(page, queryWrapper);
        List<MomentCommentEntity> list = pageList.getRecords();
        List<String> firstUidList = new ArrayList<>();
        list.forEach(item -> {
            firstUidList.add(item.getUid());
        });
        if (firstUidList.size() > 0) {
            // 查询一级评论下的子评论
            QueryWrapper<MomentCommentEntity> notFirstQueryWrapper = new QueryWrapper<>();
            notFirstQueryWrapper.in(SQLConf.FIRST_COMMENT_UID, firstUidList);
            notFirstQueryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
            notFirstQueryWrapper.orderByDesc(SQLConf.CREATE_TIME);
            List<MomentCommentEntity> notFirstList = this.list(notFirstQueryWrapper);
            // 将子评论加入总的评论中
            if (notFirstList.size() > 0) {
                list.addAll(notFirstList);
            }
        }
        List<String> userUidList = new ArrayList<>();
        list.forEach(item -> {
            String userUid = item.getCreateUserUid();
            String toUserUid = item.getToUserUid();
            if (StringUtils.isNotEmpty(userUid)) {
                userUidList.add(item.getCreateUserUid());
            }
            if (StringUtils.isNotEmpty(toUserUid)) {
                userUidList.add(item.getToUserUid());
            }
        });
        Collection<UserDto> userList = new ArrayList<>();
        if (userUidList.size() > 0) {
            R userResult = userFeignClient.listUserByUids(userUidList);
            if (userResult.getCode() == 0) {
                userList = userResult.getData(new TypeReference<List<UserDto>>(){});
            }else {
                throw new FeignException("feign调用异常（根据用户id列表找用户）：失败");
            }
        }
        // 过滤掉用户的敏感信息
        List<UserDto> filterUserList = userUtil.convertUserList(userList);
        // 获取用户头像
        List<String> fileUidList = new ArrayList<>();
        filterUserList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar())) {
                fileUidList.add(item.getAvatar());
            }
        });
        Map<String, String> pictureMap = fileFeignUtil.fileUidToFileUrlMap(fileUidList);

        Map<String, UserDto> userMap = new HashMap<>();
        filterUserList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar()) && pictureMap.get(item.getAvatar()) != null) {
                item.setPhotoUrl(pictureMap.get(item.getAvatar()));
            }
            userMap.put(item.getUid(), item);
        });
        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getCreateUserUid())) {
                item.setUser(userMap.get(item.getCreateUserUid()));
            }
            if (StringUtils.isNotEmpty(item.getToUserUid())) {
                item.setToUser(userMap.get(item.getToUserUid()));
            }
        });
        return pageList;
    }

    /**
     * 根据id获取榜单成员评论
     *
     * @param uid
     * @return
     */
    @Override
    public MomentCommentEntity getCommentById(String uid) {
        return this.getOne(
                new LambdaQueryWrapper<MomentCommentEntity>()
                        .eq(MomentCommentEntity::getUid, uid)
                        .eq(MomentCommentEntity::getStatus, StatusEnum.ENABLE)
        );
    }

    /**
     * 评论下架
     *
     * @param uid
     * @return
     */
    @Override
    public Boolean revocationComment(String uid) {
        return momentCommentDao.revocationComment(uid, "因举报过多暂时下架", AuditStatusEnum.REJECT);

    }

    /**
     * 获取评论数目
     *
     * @param createUserUid
     * @param momentUid
     * @param toUserUid
     * @author
     * @date 2023年10月22日下午3:43:38
     */
    @Override
    public Integer getCommentCount(String createUserUid, String momentUid, String toUserUid) {
        QueryWrapper<MomentCommentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(createUserUid)) {
            queryWrapper.eq(SQLConf.CREATE_USER_UID, createUserUid);
        }
        if (StringUtils.isNotEmpty(momentUid)) {
            queryWrapper.eq(SQLConf.MOMENT_UID, momentUid);
        }
        if (StringUtils.isNotEmpty(toUserUid)) {
            queryWrapper.eq(SQLConf.TO_USER_UID, toUserUid);
        }
        queryWrapper.eq(BaseSQLConf.STATUS, StatusEnum.ENABLE);
        return momentCommentDao.selectCount(queryWrapper);
    }


    // endregion
    /***************************** web:end **************************/

    @Override
    public Map<String, List<MomentCommentEntity>> getCommentMapByBusinessId(MomentCommentDto momentCommentDto) {
        QueryWrapper<MomentCommentEntity> queryWrapper = new QueryWrapper<>();
        Map<String, List<MomentCommentEntity>> businessCommentMap = new HashMap<>();
        List<String> businessUidList = momentCommentDto.getBusinessUidList();
        if (businessUidList != null && businessUidList.size() > 0) {
            queryWrapper.in(SQLConf.MOMENT_UID, businessUidList);
        } else {
            return businessCommentMap;
        }
        queryWrapper.eq(SQLConf.SOURCE, momentCommentDto.getSource());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        queryWrapper.eq(SQLConf.TYPE, CommentTypeEnum.COMMENT);
        // 查询出该文章下所有的评论
        List<MomentCommentEntity> list = this.list(queryWrapper);
        List<String> toCommentUidList = new ArrayList<>();
        // 判断回复评论的UID
        list.forEach(item -> {
            toCommentUidList.add(item.getToUid());
        });
        // 定义一个数组，用来存放全部的评论
        List<MomentCommentEntity> allCommentList = new ArrayList<>();
        allCommentList.addAll(list);
        // 查询出回复的评论
        Collection<MomentCommentEntity> toCommentList = null;
        if (toCommentUidList.size() > 0) {
            toCommentList = this.listByIds(toCommentUidList);
            allCommentList.addAll(toCommentList);
        }
        // 查询出评论用户的基本信息
        List<String> userUidList = new ArrayList<>();
        allCommentList.forEach(item -> {
            String userUid = item.getCreateUserUid();
            String toUserUid = item.getToUserUid();
            if (StringUtils.isNotEmpty(userUid)) {
                userUidList.add(item.getCreateUserUid());
            }
            if (StringUtils.isNotEmpty(toUserUid)) {
                userUidList.add(item.getToUserUid());
            }
        });
        List<UserDto> userList = new ArrayList<>();
        if (userUidList.size() > 0) {
            R result = userFeignClient.listUserByUids(userUidList);
            if(result.getCode()==0){
                userList = result.getData(new TypeReference<List<UserDto>>(){});
            }else {
                throw new FeignException("feign调用异常（通过ids获取用户列表【携带用户头像和背景图片】）：失败");
            }
        }
// 过滤敏感信息
        List<UserDto> filterUserList = new ArrayList<>();
        userList.forEach(item -> {
            filterUserList.add(convertUser(item));
        });

        // 获取用户头像
        List<String> fileUidList = new ArrayList<>();
        filterUserList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar())) {
                fileUidList.add(item.getAvatar());
            }
        });
        Map<String, String> pictureMap = fileFeignUtil.fileUidToFileUrlMap(fileUidList);

        Map<String, UserDto> userMap = new HashMap<>();
        filterUserList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar()) && pictureMap.get(item.getAvatar()) != null) {
                item.setPhotoUrl(pictureMap.get(item.getAvatar()));
            }
            userMap.put(item.getUid(), item);
        });

        // 定义一个评论Map键值对
        Map<String, MomentCommentEntity> commentMap = new HashMap<>();
        allCommentList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getCreateUserUid())) {
                item.setUser(userMap.get(item.getCreateUserUid()));
            }
            if (StringUtils.isNotEmpty(item.getToUserUid())) {
                item.setToUser(userMap.get(item.getToUserUid()));
            }

//            // 设置点赞相关信息
//            UserPraiseRecordVO userPraiseRecordVO = new UserPraiseRecordVO();
//            userPraiseRecordVO.setResourceUid(item.getUid());
//            userPraiseRecordVO.setResourceType(EResourceType.COMMENT.getType());
//            Map<String, Object> praiseMap = userPraiseRecordService.praisedCount(userPraiseRecordVO);
//            item.setPraiseInfo(praiseMap);
//
//            // 设置收藏相关信息
//            CollectVO collectVO = new CollectVO();
//            collectVO.setBizUid(item.getUid());
//            collectVO.setCollectType(EResourceType.COMMENT.getType());
//            Map<String, Object> collectInfo = collectService.getCollectCount(collectVO);
//            item.setCollectInfo(collectInfo);

            commentMap.put(item.getUid(), item);
        });

        // 给查询出来的评论添加基本信息
        list.forEach(item -> {

            String commentUid = item.getUid();
            String toCommentUid = item.getToUid();
            MomentCommentEntity comment = commentMap.get(commentUid);
            if (StringUtils.isNotEmpty(toCommentUid)) {
                comment.setToComment(commentMap.get(toCommentUid));
            }

            String momentUid = item.getMomentUid();
            List<MomentCommentEntity> commentList = businessCommentMap.get(momentUid);
            if (commentList != null) {
                commentList.add(comment);
                businessCommentMap.put(momentUid, commentList);
            } else {
                List<MomentCommentEntity> tempCommentList = new ArrayList<>();
                tempCommentList.add(comment);
                businessCommentMap.put(momentUid, tempCommentList);
            }

        });
        return businessCommentMap;
    }

    private UserDto convertUser(UserDto item) {
        UserDto user = new UserDto();
        user.setUid(item.getUid());
        user.setAvatar(item.getAvatar());
        user.setPhotoUrl(item.getPhotoUrl());
        user.setNickname(item.getNickname());
        user.setOccupation(item.getOccupation());
        user.setSummary(item.getSummary());
        user.setCreateTime(item.getCreateTime());
        user.setLoadingValid(item.getLoadingValid());
        user.setStatus(item.getStatus());
        user.setGender(item.getGender());
        user.setUserTag(item.getUserTag());
        user.setCredits(item.getCredits());
        user.setExpValue(item.getExpValue());
        user.setUserLevel(UserLevelEnum.getLvByExpValue(item.getExpValue()).getLevel());
        user.setBackgroundFileUrl(item.getBackgroundFileUrl());
        user.setBackgroundFileUid(item.getBackgroundFileUid());

        // 过滤用户
        String ip = item.getLastLoginIp();
        String ipPossession = redisUtil.get(RedisConf.USER_IP_POSSESSION + Constants.SYMBOL_COLON + user.getUid());
        if (StringUtils.isEmpty(ipPossession) && StringUtils.isNotEmpty(ip)) {
            // ip属地
            ipPossession = IpUtils.getIpPossession(ip);
            // 将信息设置到redis中
            redisUtil.setEx(RedisConf.USER_IP_POSSESSION + Constants.SYMBOL_COLON + user.getUid(), ipPossession, 1, TimeUnit.HOURS);
        }
        user.setUserIpPossession(ipPossession);
        return user;
    }


    /**
     * 审批评论
     *
     * @param momentCommentDto
     * @return
     */
    @Override
    public String auditComment(MomentCommentDto momentCommentDto) {
        MomentCommentEntity comment = this.getById(momentCommentDto.getUid());

        comment.setAuditStatus(momentCommentDto.getAuditStatus());
        comment.setRejectReason(momentCommentDto.getRejectReason());
        if(StringUtils.isEmpty(comment.getAuditName())) {

            //  通过feign获取 admin
            String nickname;
            R adminResult = adminFeignClient.getAdminNicknameById(RequestHolder.getAdminUid());
            if(adminResult.getCode()==0){
                nickname = adminResult.getData(new TypeReference<String>(){});
                // 将系统配置存入Redis中【设置过期时间24小时】
//                    redisUtil.setEx(RedisConf.SYSTEM_CONFIG, JsonUtils.objectToJson(systemConfig), 24, TimeUnit.HOURS);
            }else {
                // 获取异常信息
                String msg = adminResult.getData("msg",new TypeReference<String>(){});
                throw new FeignException("feign调用异常（获取系统配置）："+msg);
            }
            comment.setAuditName(nickname);
        }
        comment.setAuditTime(new Date());
        boolean isSave = this.updateById(comment);
        if (isSave) {
            MomentCommentDto dto = new MomentCommentDto();
            BeanUtils.copyProperties(comment, dto);
            domainEventUtil.publishEvent(EventAction.MOMENT_COMMENT_AUDIT, dto);
        }
        return ResultUtil.successWithMessage(MessageConf.OPERATION_SUCCESS);
    }

    /**
     * 根据id集合查询评论
     *
     * @param uidList
     * @return
     */
    @Override
    public List<MomentCommentEntity> getCommentPageListByIds(Collection<String> uidList) {
        Collection<MomentCommentEntity> commentCollection = this.listByIds(uidList);
        return this.convertCommentList(commentCollection);
    }

    /**
     * 添加评论（当该评论不是一级评论时，需要设置一级评论UID字段）
     *
     * @param comment
     * @return
     */
    @Override
    public MomentCommentEntity addCommentWithFirstCommentUid(MomentCommentDto commentDto) {
        MomentCommentEntity comment = new MomentCommentEntity();
        BeanUtils.copyProperties(commentDto, comment);
        // 当该评论不是一级评论时，需要设置一级评论UID字段
        // 非一级评论，才需要设置toUserUid
        if (StringUtils.isNotEmpty(comment.getToUid())) {
            MomentCommentEntity toComment = this.getById(comment.getToUid());
            assert toComment != null;
            // 表示 toComment 是非一级评论
            if (StringUtils.isNotEmpty(toComment.getFirstCommentUid())) {
                comment.setFirstCommentUid(toComment.getFirstCommentUid());
            } else {
                // 表示父评论是一级评论，直接获取UID
                comment.setFirstCommentUid(toComment.getUid());
            }

        }else if(null!=comment.getToUserUid()){
            // 一级评论，不需要设置toUserUid
            comment.setToUserUid(null);
        }

        comment.insert();
        return comment;
    }

    /**
     * 根据条件查询评论列表
     *
     * @param page
     * @param comment
     * @return
     */
    @Override
    public IPage<MomentCommentEntity> queryPageWithMoment(Page<MomentCommentEntity> page, MomentCommentDto comment) {
        Page<MomentCommentEntity> pageList = momentCommentDao.queryPageWithMoment(page, comment);
        return pageList;
    }
}